import {action, configure, observable, runInAction} from "mobx"
import CodePush from "react-native-code-push"
import {logger} from "../utils/util"
import api from '../net/api';
import DeviceInfo from "react-native-device-info";
import {isAndroid} from '../configs/platform';

// 安装包最新信息
export const versionUptodateInfo = {
  version: '1.1.33',
  downloadUrl: 'https://xmbzccb.oss-cn-shenzhen.aliyuncs.com/apps/panda_release_1.1.33_20230719.apk',
}

configure({
  enforceActions: "always"
})

class Store {
  @observable showUpgrade = false
  @observable versionInfo = versionUptodateInfo
  @observable updateInfo = null

  @action.bound
  setValue(keys, data) {
    this[keys] = data
  }

  @action.bound
  versionCheck(showTips=false) {
    this.checkHotPatch(showTips)
    this.checkAndroidVersion()
    // axios.post(api.version)
    //   .then(res => {
    //     runInAction(() => {
    //       logger('检测更新',res.data)
    //       if(res.data)
    //       {
    //         this.versionInfo = res.data
    //         this.showUpgrade = DeviceInfo.getBuildNumber()<res.data.versionNum
    //         if (!this.showUpgrade) {
    //           logger('检测补丁',showTips)
    //           this.checkHotPatch(showTips)
    //         }
    //       }
    //       else{
    //         this.versionInfo =null;
    //         this.showUpgrade =null;
    //         this.checkHotPatch(showTips)
    //       }
    //     })
    //   }).catch(() => {
    //   runInAction(() => {
    //     this.versionInfo =null;
    //     this.showUpgrade =null;
    //     this.checkHotPatch(showTips)
    //   })
    // })
  }

  @action.bound
  checkHotPatch = (showTips=false) => {
    CodePush.checkForUpdate()
      .then((update) => {
        runInAction(() => {
          if (!update) {
            logger("无新的补丁")
            if(showTips)
            {
              Toast.show('已是最新版本')
            }
            this.updateInfo =null;
          } else {
            this.updateInfo = update
            logger("有新的补丁", JSON.stringify(update))
          }
        })

    }).catch((err) => {
      runInAction(() => {
        logger('热更新', err);
        this.updateInfo =null;
        if(showTips)
        {
          Toast.show('已是最新版本')
        }
      })
    })
  }

  @action.bound
  checkAndroidVersion = () => {
    if (isAndroid() && DeviceInfo.getVersion() != versionUptodateInfo.version) {
      runInAction(() => {
        this.showUpgrade = true
        this.versionInfo = {
          ...versionUptodateInfo,
          remark: '点击【立即升级】下载最新安装包'
        }
      })
    }
  }
}

export default new Store()
